﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using Keyboard.Properties;
using CommandReceiver;
using Common;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace Keyboard
{
    public partial class Form1 : Form
    {
        //定义一个NotifyIcon对象 
        private System.Windows.Forms.NotifyIcon notifyIcon1;
        TcpServer server = null;
        SeperatePack sp = new SeperatePack();

        public Form1()
        {
            InitializeComponent();

            //创建NotifyIcon对象并设置其基本的属性如Icon，Text及Visible等 
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon();//this.components);
            this.notifyIcon1.Icon = (System.Drawing.Icon)Resources.abiword_2;
            //this.notifyIcon1.Text = "这是我的测试程序，还Cool吧！";
            this.notifyIcon1.Visible = true;
            //SendKeys.Send(e.Key);
            //Cursor.Position = new Point(e.DeltaX, e.DeltaY);
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            this.Text = "控制服务台 - " + Dns.GetHostByName("localhost").AddressList[0].ToString();
            //生成4个菜单项对象，显示文本分别为"显示窗口"、"隐藏窗口"、"执行程序"、"退出程序" 
            MenuItem menuItem1 = new MenuItem("显示窗口");
            MenuItem menuItem2 = new MenuItem("隐藏窗口");
            MenuItem menuItem3 = new MenuItem("执行程序");
            MenuItem menuItem4 = new MenuItem("退出程序");
            //分别为4个菜单项添加Click事件响应函数 
            menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
            menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
            menuItem3.Click += new System.EventHandler(this.menuItem3_Click);
            menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
            //设置NotifyIcon对象的ContextMenu属性为生面的弹出菜单对象 
            notifyIcon1.ContextMenu = new ContextMenu(new MenuItem[] { menuItem1, menuItem2, menuItem3, menuItem4 });
            //当用户双击程序图标时将执行相应的函数 
            notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon_DBClick);

            server = new TcpServer(6004);
            server.Accept += new TcpAcceptEventHandler(server_Accept);
            server.Start();
        }

        private void server_Accept(object sender, System.Net.Sockets.Socket socket)
        {
            try
            {
                byte[] bs = System.Text.Encoding.Default.GetBytes("ok");
                socket.Send(bs);
                while (true)
                {
                    byte[] receive = new byte[1024];
                    socket.Receive(receive);
                    sp.Text = System.Text.Encoding.UTF8.GetString(receive);
                    foreach (var item in sp)
                    {
                        Command c = Parse(item);
                        switch (c.Type)
                        {
                            case "keyboardd":
                                SendKeys.SendWait(c.Commands[0].Value.ToLower());
                                break;
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                //socket.Close();
                //server.Stop();
            }
        }

        private void menuItem1_Click(object sender, System.EventArgs e)//“显示窗口”菜单的响应方法 
        {
            if (this.Visible == false) this.Visible = true;//假如当前窗口没显示则显示当前窗口 
        }

        private void menuItem2_Click(object sender, System.EventArgs e)//"隐藏窗口"菜单的响应方法 
        {
            if (this.Visible == true) this.Visible = false;//假如当前窗口为显示的则隐藏窗口 
        }

        private void menuItem3_Click(object sender, System.EventArgs e)//"执行程序"菜单的响应方法 
        {
            //显示一个提示信息框，表示事件已经得到响应 
            MessageBox.Show("演示程序已经执行，此处功能就是显示一个提示框！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void menuItem4_Click(object sender, System.EventArgs e)//“退出程序”菜单的响应方法 
        {
            CloseApp();
        }

        private void notifyIcon_DBClick(object sender, System.EventArgs e)//用户双击应用程序图标进的响应方法 
        {
            this.Visible = true;//显示当前主窗口 
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            CloseApp();
        }

        private void btnHide_Click(object sender, EventArgs e)
        {
            this.Visible = false;//隐藏当前主窗口 
        }

        private void CloseApp()
        {
            notifyIcon1.Dispose();
            server.Stop();
            this.Close();//关闭当前对象(即窗体) 
            Application.Exit();//通过Application类的静态方法Exit()退出应用程序 
        }

        private Command Parse(string xml)
        {
            Command c = new Command();
            xml = xml.Replace("\0", " ");
            XDocument doc = XDocument.Parse(xml, LoadOptions.SetLineInfo);
            c.Type = doc.Element("root").Element("type").Value;
            c.Operation = doc.Element("root").Element("operation").Value;
            foreach (XElement item in doc.Element("root").Element("commands").Elements())
            {
                c.Commands.Add(new CommandItem()
                {
                    Name = item.Attribute("name").Value,
                    Value = item.Attribute("value").Value
                });
            }

            return c;
        }

    }

    public class SeperatePack : IEnumerable<string>
    {
        private string prev = string.Empty;
        private string g1 = string.Empty;
        private string gentire = string.Empty;
        private string g3 = string.Empty;

        Regex r1 = new Regex(@"^(?:.*)(<\?xml.*</root>)(?:.*)$", RegexOptions.Singleline);
        Regex r2 = new Regex(@"^<\?xml.*</root>$", RegexOptions.Singleline);

        public string Text { get; set; }

        public IEnumerator<string> GetEnumerator()
        {
            string total = prev + Text;
            Match m = r1.Match(Text);

            string[] arr = m.Groups[1].Value.Split(new string[] { "</root>" }, StringSplitOptions.RemoveEmptyEntries);
            prev = m.Groups.Count == 3 ? m.Groups[2].Value : string.Empty;
            for (int i = 0; i < arr.Length; i++)
            {
                string str = arr[i] + "</root>";
                if (r2.IsMatch(str))
                {
                    yield return str;
                }
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            string total = prev + Text;
            Match m = r1.Match(Text);

            for (int i = 1; i < m.Groups.Count; i++)
            {
                if (i == m.Groups.Count)
                {
                    prev = r2.IsMatch(m.Groups[i].Value) ? string.Empty : m.Groups[i].Value;
                }

                if (r2.IsMatch(m.Groups[i].Value))
                {
                    yield return m.Groups[i].Value;
                }
            }
        }
    }
}